package cn.zhaoyan.daoimpl;



import cn.zhaoyan.bean.User;
import cn.zhaoyan.dao.Userdao;
import cn.zhaoyan.util.Jdbcutils;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.Date;

public class UserDaoImpl implements Userdao {
    private JdbcTemplate jdbcTemplate = new JdbcTemplate(Jdbcutils.getDataSource());

    /**
     * 登录查询比对数据库中的账号密码
     * @param user
     * @return
     */
    @Override
    public User userDaodl(User user) {
        try {
            String sql="SELECT*FROM user where name =? and password =? and role = ? ";
            return this.jdbcTemplate.queryForObject(sql,new BeanPropertyRowMapper<>(User.class),user.getName(),user.getPassword(),user.getRole());
        } catch (
                DataAccessException e) {
            return null;
        }
    }

    /**
     * 注册查询数据库有没有重复注册时候调用，所以只用查询用户名
     * @param user
     * @return
     */



    @Override
    public User userDao(User user) {
        try {
            String sql="SELECT*FROM user where name =?and role = ?";
            return  this.jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<>(User.class), user.getName(),user.getRole());
        } catch (DataAccessException e) {
            return null;
        }
    }

    /**
     * 往数据库添加数据注册时候调用
     * @param user
     * @return
     */
    @Override
    public int regist(User user) {
        try {
            String sql = "INSERT  INTO `yan`.`user`( `name`, `password`, `newtime`, `updatatime`, `role`) VALUES (?,?,?,?,?)";
            int update = this.jdbcTemplate.update(sql, user.getName(), user.getPassword(), new Date(), new Date(),user.getRole());
            return update;
        } catch (DataAccessException e) {
            return 0;

        }

    }

}
